import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import { Toast } from 'vant';
import moment from 'moment';

Vue.prototype.$moment = moment; //挂载

Vue.use(Toast);

//引入axios
import axios from 'axios';
import VueAxios from 'vue-axios';
axios.defaults.baseURL = 'http://localhost:3000/';
Vue.use(VueAxios, axios);

// 添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
  config => {
    if (localStorage.getItem('token')) {
      config.headers.token = localStorage.getItem('token');
    }

    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

//配置响应的参数
axios.interceptors.response.use(
  response => {
    //当token过期或者不存在时，后台返回状态码401，此时页面跳转到登录页面
    if (response.status === 401) {
      Toast.fail('登录信息已过期,请重新登录');
      router.push({ path: '/login' });
    }
    return response;
  },
  error => {
    return Promise.reject(error);
  }
);

//引入vant组件库
import Vant from 'vant';
import 'vant/lib/index.css';
Vue.use(Vant);
import { Lazyload } from 'vant';
Vue.use(Lazyload);

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app');

//设置rem  以iphone7为标准, 宽375px   设置1rem=10px
const setFontSize = () => {
  const htmlDom = document.getElementsByTagName('html')[0];
  let htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
  if (htmlWidth >= 750) {
    htmlWidth = 750;
  }
  if (htmlWidth <= 320) {
    htmlWidth = 320;
  }
  htmlDom.style.fontSize = `${htmlWidth / 37.5}px`;
};
window.onresize = setFontSize;
setFontSize();
